using FytSoa.Domain.Sys;
using FytSoa.Sugar;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoMapper;
using FytSoa.Common.Utils;
using FytSoa.Domain.Core.Param;
using FytSoa.Domain.Core.Result;
using Masuit.Tools.Linq;
using Microsoft.AspNetCore.Mvc;

namespace FytSoa.Application.Sys
{
    /// <summary>
    /// 授权表服务接口
    /// </summary>
    [ApiExplorerSettings(GroupName = "v1")]
    public class SysAuthorityService : SugarRepository<SysAuthority>,ISysAuthorityService 
    {
        private readonly IMapper _mapper;
        public SysAuthorityService(IMapper mapper)
        {
            _mapper = mapper;
        }
        
        
        /// <summary>
        /// 根据角色获得权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("{roleId}")]
        public async Task<ApiResult<List<SysAuthorityDto>>> GetByRoleAsync(long roleId)
        {
            return JResult<List<SysAuthorityDto>>.Success(_mapper.Map<List<SysAuthorityDto>>(await base.GetListAsync(m=>m.RoleId==roleId,m=>m.MenuId)));
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> AddAsync(SysAuthorityParam model)
        {
            await base.DeleteAsync(m => m.RoleId == model.RoleId && m.Types == 3);
            var list = new List<SysAuthority>();
            foreach (var item in model.Menus)
            {
                list.Add(new SysAuthority()
                {
                    RoleId = model.RoleId,
                    MenuId = item.MenuId,
                    BtnFun = item.BtnFun,
                    Types = 3
                });
            }
            return JResult<bool>.Success(await base.InsertRangeAsync(list));
        }

    }
}
